package com.itheima.controller;

import com.itheima.controller.groups.GroupA;
import com.itheima.domain.Employee;

import com.itheima.domain.Employee2;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

import javax.validation.Valid;

@Controller
public class EmployeeController {

    @PostMapping("/addemployee")
    public String addEmployee(Employee employee, Model model) {
        if (employee.getName() == null || employee.getName().length() == 0) {
            model.addAttribute("name", "name 不可为空");
            return "error.jsp";
        }
        if (employee.getAge() == null) {
            model.addAttribute("age", "age 不可为空");
            return "error.jsp";
        }
        if (employee.getAge() < 14) {
            model.addAttribute("age", "age 不得小于14");
            return "error.jsp";
        }
        return "success.jsp";
    }

    @PostMapping("/addemployee1")
    public String addEmployee1(@Valid Employee employee, Errors errors, Model m) {
        if (errors.hasErrors()) {
            List<FieldError> fieldErrors = errors.getFieldErrors();
            System.out.println("fieldErrors.size: " + fieldErrors.size());
            for (FieldError error : fieldErrors) {
                System.out.println("field: " + error.getField());
                System.out.println("defaultMessage: " + error.getDefaultMessage());
                m.addAttribute(error.getField(), error.getDefaultMessage());
            }
            return "addemployee.jsp";
        }
        return "success.jsp";
    }

    @RequestMapping("/addemployee2")
    public String addEmployee2(@Validated({GroupA.class}) Employee2 employee, Errors errors, Model m) {
        if (errors.hasErrors()) {
            List<FieldError> fieldErrors = errors.getFieldErrors();
            System.out.println("fieldErrors.size: " + fieldErrors.size());
            for (FieldError error : fieldErrors) {
                System.out.println("field: " + error.getField());
                System.out.println("defaultMessage: " + error.getDefaultMessage());
                m.addAttribute(error.getField(), error.getDefaultMessage());
            }
            return "addemployee.jsp";
        }
        return "success.jsp";
    }

}